package com.bc.plugin.doc.resolver.param;

import com.bc.plugin.doc.builder.BuilderConfig;
import com.bc.plugin.doc.dto.FieldClassDTO;
import com.bc.plugin.doc.resolver.IApiParamHandle;
import com.power.common.util.CollectionUtil;
import com.power.common.util.StringUtil;
import com.power.doc.constants.DocGlobalConstants;
import com.power.doc.model.ApiConfig;
import com.power.doc.model.ApiParam;
import com.power.doc.model.CustomRespField;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CustomRespFieldApiParamHandle implements IApiParamHandle {
    Map<String, CustomRespField> responseFieldMap;

    public static Map<String, CustomRespField> toMap(List<CustomRespField> customRespFieldList) {
        Map<String, CustomRespField> responseFieldMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(customRespFieldList)) {
            for (CustomRespField field : customRespFieldList) {
                responseFieldMap.put(field.getName(), field);
            }
        }
        return responseFieldMap;
    }

    @Override
    public void init(ApiConfig apiConfig, BuilderConfig builderConfig) {
        responseFieldMap = CustomRespFieldApiParamHandle.toMap(apiConfig.getCustomResponseFields());
    }

    @Override
    public ApiParam handle(ApiParam apiParam, FieldClassDTO fieldClassDTO, boolean isResponse) {
        if (isResponse) {
            //cover comment
            CustomRespField customResponseField = responseFieldMap.get(apiParam.getField());
            if (null != customResponseField && StringUtil.isNotEmpty(customResponseField.getDesc())) {
                if (customResponseField.isForceReplace() || StringUtil.isEmpty(apiParam.getDesc())) {
                    apiParam.setDesc(customResponseField.getDesc());
                }
            }
        }
        return apiParam;
    }
}
